<?php

namespace App\Cache\Project;

use App\Services\Project\ProjectService;
use Illuminate\Support\Facades\Cache;
use Psr\SimpleCache\InvalidArgumentException;

/**
 * 管理缓存
 */
class ProjectCache
{
    // 缓存标签
    public static string $tag = 'project';
    // 缓存前缀
    protected static string $prefix = 'project:';

    /**
     * 缓存键名
     *
     * @param mixed $id id、key
     *
     * @return string
     */
    private static function key($id): string
    {
        return self::$prefix . $id;
    }

    /**
     * 缓存设置
     *
     * @param mixed $id id、key
     * @param $info
     * @param int $ttl 有效时间（秒，0永久）
     *
     * @return bool
     */
    public static function set($id,  $info, int $ttl = 604800): bool
    {
        return Cache::tags(self::$tag)->put(self::key($id), $info, $ttl);
    }


    /**
     * Notes:该数据在缓存里是否存在
     * DateTime: 2023/8/18 17:15
     * Author: tzhe
     * @param $id
     * @return bool
     */
    public function has($id): bool
    {
        return Cache::has(self::key($id));
    }

    /**
     * 缓存获取
     *
     * @param mixed $id id、key
     *
     */
    public static function get($id)
    {
        return Cache::tags(self::$tag)->get(self::key($id));
    }

    /**
     * 删除缓存
     *
     * @param mixed $id id、key
     *
     * @return bool
     */
    public static function forget($id = ''): bool
    {
        $ids = var_to_array($id);
        foreach ($ids as $v) {
            Cache::tags(self::$tag)->forget(self::key($v));
        }
        return true;
    }

    /**
     * 缓存更新
     *
     * @param mixed $id id
     *
     * @return void
     * @throws InvalidArgumentException
     */
    public static function update($id)
    {
        $ids = var_to_array($id);
        foreach ($ids as $v) {
            $old = self::get($v);
            if ($old) {
                self::forget($v);
                /** @var ProjectService $projectService */
                $projectService = app('App\Services\Project\ProjectService');
                $new = $projectService->getInstance($v);
                if ($new) {
                    self::set($v, $new);
                }
            }
        }
    }

    /**
     * Notes:清楚项目下所有缓存
     * DateTime: 2023/8/25 13:33
     * Author: tzhe
     * @return bool
     */
    public static function clear(): bool
    {
        return Cache::tags(self::$tag)->flush();
    }

}
